package cn.itsource.service;

import lombok.Data;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;

import javax.mail.internet.MimeMessage;

/**
 * @program fccar_240420
 * @Description
 * @Date 2024/09/13 11:27
 * @Version 1.0
 */
@Data
public class EmailTemplate {
    private JavaMailSender javaMailSender;

    public EmailTemplate(JavaMailSender javaMailSender) {
        this.javaMailSender = javaMailSender;
    }

    public void simpleSendEmail(String fromEmail,String toEmail,String title,String content){
        SimpleMailMessage mailMessage = new SimpleMailMessage();
        //设置发送人
        mailMessage.setFrom(fromEmail);
        //邮件主题
        mailMessage.setSubject(title);
        //邮件内容：普通文件无法解析html标签
        mailMessage.setText(content);
        //收件人
        mailMessage.setTo(toEmail);
        //发送邮件
        javaMailSender.send(mailMessage);
    }

    public void complexSendEmail(String fromEmail,String toEmail,String title,String content,Object ...objects){
        try {
            //创建复杂邮件对象
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            //发送复杂邮件的工具类
            //true - 能够添加附件
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true,"utf-8");
            helper.setFrom(fromEmail);
            helper.setSubject(title);
            //true - 能够再内容中编写html标签 - 会解析
            helper.setText(content,true);
            //添加附件
            // helper.addAttachment("p7.jpg",new File("C:\\Users\\Administrator\\Pictures\\photos\\p7.jpg"));
            // helper.addAttachment("g1.gif", new File("C:\\Users\\Administrator\\Pictures\\g1.gif"));
            //收件人
            helper.setTo(toEmail);
            javaMailSender.send(mimeMessage);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
